<template>
	<div class="user-management-container">
		<!-- 面包屑导航 -->
		<el-breadcrumb separator="/" class="el-breadcrumb">
			<el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
			<el-breadcrumb-item>用户管理</el-breadcrumb-item>
		</el-breadcrumb>

		<!-- 搜索区域 -->
		<el-form :inline="true" :model="queryParams" class="search-form" label-width="70px">
			<el-form-item label="用户名">
				<el-input v-model="queryParams.username" placeholder="请输入用户名" clearable @clear="queryDataList"
					:prefix-icon="Search" style="width: 240px" size="large" />
			</el-form-item>
			<el-form-item label="手机号">
				<el-input v-model="queryParams.mobile" placeholder="请输入手机号" clearable @clear="queryDataList"
					:prefix-icon="Search" style="width: 240px" size="large" />
			</el-form-item>
			<el-form-item>
				<el-button type="primary" class="operation-btn" @click="queryDataList">搜索</el-button>
				<el-button type="primary" class="operation-btn" @click="handleAdd">新增用户</el-button>
				<el-button type="danger" class="operation-btn" @click="batchRemove"
					:disabled="multipleSelection.length === 0" :loading="batchLoading">
					批量删除
				</el-button>
			</el-form-item>
		</el-form>

		<!-- 用户表格 -->
		<el-table :data="dataList" :loading="tableLoading" border row-key="id" style="width: 100%; margin-top: 15px"
			@selection-change="handleSelectionChange">
			<el-table-column type="selection" width="55" />
			<el-table-column prop="id" label="ID" width="80" />
			<el-table-column prop="username" label="用户名" />
			<el-table-column prop="mobile" label="手机号" />
			<el-table-column prop="nickname" label="昵称" />
			<el-table-column prop="email" label="邮箱" />
			<!-- 状态显示：确保基于最新del值判断 -->
			<el-table-column label="状态" width="100">
				<template #default="scope">
					<el-tag :type="scope.row.del === 0 ? 'success' : 'danger'">
						{{ scope.row.del === 0 ? '正常' : '停用' }}
					</el-tag>
				</template>
			</el-table-column>
			<el-table-column fixed="right" label="操作" min-width="180">
				<template #default="scope">
					<el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDelete(scope.row.id)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!-- 分页控件 -->
		<el-pagination v-model:current-page="queryParams.pageNum" v-model:page-size="queryParams.pageSize"
			:page-sizes="[5, 10, 15, 20]" layout="total, sizes, prev, pager, next, jumper" :total="total"
			@size-change="handleSizeChange" @current-change="handleCurrentChange"
			style="margin-top: 15px; text-align: right" />

		<!-- 用户表单对话框 -->
		<el-dialog v-model="dialogVisible" :title="dialogTitle" width="600px" :before-close="handleDialogClose">
			<el-form :model="userForm" label-width="80px" class="dialog-form">
				<el-form-item label="用户名" required>
					<el-input v-model="userForm.username" placeholder="请输入用户名" size="large" style="width: 100%" />
				</el-form-item>
				<el-form-item label="手机号">
					<el-input v-model="userForm.mobile" placeholder="请输入手机号" size="large" style="width: 100%" />
				</el-form-item>
				<el-form-item label="昵称">
					<el-input v-model="userForm.nickname" placeholder="请输入昵称" size="large" style="width: 100%" />
				</el-form-item>
				<el-form-item label="邮箱">
					<el-input v-model="userForm.email" placeholder="请输入邮箱" size="large" style="width: 100%" />
				</el-form-item>
				<el-form-item label="密码" :required="!isEditMode">
					<el-input v-model="userForm.password" type="password" show-password size="large" style="width: 100%"
						:placeholder="isEditMode ? '请输入修改的密码' : '请输入密码（不少于6位）'" />
				</el-form-item>
				<!-- 状态选择：绑定 del 字段 -->
				<el-form-item label="状态">
					<el-select v-model="userForm.del" placeholder="选择用户状态" size="large" style="width: 100%">
						<el-option label="正常" value="0" />
						<el-option label="停用" value="1" />
					</el-select>
				</el-form-item>
			</el-form>
			<template #footer>
				<div class="dialog-footer">
					<el-button @click="handleDialogClose">取消</el-button>
					<el-button type="primary" @click="confirmSave">确定</el-button>
				</div>
			</template>
		</el-dialog>
	</div>
</template>

<script lang="ts" setup>
	import { ElMessage, ElMessageBox } from 'element-plus';
	import { getCurrentInstance, onMounted, reactive, ref } from 'vue';
	import { Search } from '@element-plus/icons-vue';

	// User 接口定义
	interface User {
		id ?: number;
		username : string;
		mobile ?: string;
		nickname ?: string;
		email ?: string;
		del : number; // 0-正常，1-停用
		password ?: string;
	}

	// 全局 axios 实例
	const axios = getCurrentInstance()?.appContext.config.globalProperties.axios;

	// 查询参数
	const queryParams = reactive({
		username: '',
		mobile: '',
		pageNum: 1,
		pageSize: 5,
	});

	// 表格数据
	const dataList = ref<User[]>([]);
	const total = ref(0);
	const tableLoading = ref(false);
	const batchLoading = ref(false);

	// 对话框状态
	const dialogVisible = ref(false);
	const dialogTitle = ref('新增用户');
	const isEditMode = ref(false);
	const userForm = ref<User>({
		username: '',
		mobile: '',
		nickname: '',
		email: '',
		del: 0,
	});

	// 批量选择数据
	const multipleSelection = ref<number[]>([]);

	// 初始化加载数据
	onMounted(() => {
		queryDataList();
	});

	// 查询数据列表（强制刷新）
	const queryDataList = () => {
		tableLoading.value = true;
		// 清除可能的缓存，确保获取最新数据
		axios
			.get('/user/page', {
				params: queryParams,
				headers: { 'Cache-Control': 'no-cache' }, // 禁用缓存
			})
			.then((resp : any) => {
				if (resp.code === 200) {
					dataList.value = resp.data.list;
					total.value = resp.data.total;
				} else {
					ElMessage.error('数据查询失败：' + (resp.msg || '未知错误'));
				}
			})
			.catch((error : any) => {
				ElMessage.error('网络请求异常：' + error.message);
			})
			.finally(() => {
				tableLoading.value = false;
			});
	};

	// 处理表格选择变化
	const handleSelectionChange = (val : User[]) => {
		multipleSelection.value = val.map((item) => item.id!).filter(Boolean);
	};

	// 分页大小变化
	const handleSizeChange = (size : number) => {
		queryParams.pageSize = size;
		queryDataList();
	};

	// 页码变化
	const handleCurrentChange = (page : number) => {
		queryParams.pageNum = page;
		queryDataList();
	};

	// 重置表单
	const resetForm = () => {
		userForm.value = {
			username: '',
			mobile: '',
			nickname: '',
			email: '',
			del: 0,
		};
		isEditMode.value = false;
		dialogVisible.value = false;
	};

	// 打开新增对话框
	const handleAdd = () => {
		dialogTitle.value = '新增用户';
		resetForm();
		dialogVisible.value = true;
	};

	// 打开编辑对话框
	const handleEdit = (row : User) => {
		dialogTitle.value = '编辑用户';
		isEditMode.value = true;
		// 深拷贝行数据，避免引用问题
		userForm.value = JSON.parse(JSON.stringify({
			...row,
			password: '', // 清空密码
		}));
		dialogVisible.value = true;
	};

	// 关闭对话框
	const handleDialogClose = () => {
		resetForm();
	};

	// 验证表单数据
	const validateForm = () : boolean => {
		if (!userForm.value.username.trim()) {
			ElMessage.warning('请输入用户名');
			return false;
		}

		if (!isEditMode.value) {
			if (!userForm.value.password) {
				ElMessage.warning('请输入密码');
				return false;
			}
			if (userForm.value.password.length < 6) {
				ElMessage.warning('密码长度不能少于6位');
				return false;
			}
		}

		return true;
	};

	// 确认保存（新增/编辑）
	const confirmSave = () => {
		if (!validateForm()) return;

		const formData = { ...userForm.value };

		// 编辑模式：密码为空则不更新密码
		if (isEditMode.value && !formData.password) {
			delete formData.password;
		}

		// 新增模式：密码为空设默认值
		if (!isEditMode.value && !formData.password) {
			formData.password = '123456';
			ElMessage.info('使用默认密码：123456');
		}

		if (isEditMode.value) {
			// 编辑成功后强制刷新数据（解决状态显示延迟）
			axios.put('/user', formData)
				.then((resp : any) => {
					if (resp.code === 200) {
						ElMessage.success('编辑成功');
						handleDialogClose();
						// 重置页码为1，确保重新加载第一页最新数据
						queryParams.pageNum = 1;
						queryDataList();
					} else {
						ElMessage.error(`编辑失败：${resp.msg || '未知错误'}`);
					}
				})
				.catch((error : any) => {
					ElMessage.error(`编辑请求失败：${error.message}`);
				});
		} else {
			axios.post('/user', formData)
				.then((resp : any) => {
					if (resp.code === 200) {
						ElMessage.success('新增成功');
						handleDialogClose();
						queryParams.pageNum = 1;
						queryDataList();
					} else {
						ElMessage.error(`新增失败：${resp.msg || '未知错误'}`);
					}
				})
				.catch((error : any) => {
					ElMessage.error(`新增请求失败：${error.message}`);
				});
		}
	};

	// 单个删除
	const handleDelete = (id : number) => {
		ElMessageBox.confirm(
			'此操作将永久删除该用户，是否继续？',
			'确认删除',
			{
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
			}
		)
			.then(() => {
				axios.delete(`/user/${id}`)
					.then((resp : any) => {
						if (resp.code === 200) {
							ElMessage.success('删除成功');
							queryDataList();
						} else {
							ElMessage.error('删除失败：' + (resp.msg || '未知错误'));
						}
					})
					.catch((error : any) => {
						ElMessage.error('删除请求失败：' + error.message);
					});
			})
			.catch(() => {
				ElMessage.info('已取消删除');
			});
	};

	// 批量删除（修改参数传递为逗号分隔字符串）
	const batchRemove = () => {
		if (multipleSelection.value.length === 0) {
			ElMessage.warning('请选择需要删除的用户');
			return;
		}

		ElMessageBox.confirm(
			`此操作将永久删除选中的${multipleSelection.value.length}个用户，是否继续？`,
			'批量删除',
			{
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
			}
		)
			.then(() => {
				batchLoading.value = true;
				// 将数组转换为逗号分隔的字符串
				const idsStr = multipleSelection.value.join(',');
				axios.delete('/user', {
					params: { ids: idsStr }
				})
					.then((resp : any) => {
						if (resp.code === 200) {
							ElMessage.success('批量删除成功');
							multipleSelection.value = [];
							queryParams.pageNum = 1;
							queryDataList();
						} else {
							ElMessage.error('批量删除失败：' + (resp.msg || '未知错误'));
						}
					})
					.catch((error : any) => {
						ElMessage.error('批量删除请求失败：' + error.message);
					})
					.finally(() => {
						batchLoading.value = false;
					});
			})
			.catch(() => {
				ElMessage.info('已取消删除');
			});
	};
</script>

<style scoped>
	.el-breadcrumb {
		padding: 15px 0;
		margin-bottom: 20px;
		border-bottom: 1px solid #eee;
	}

	.search-form {
		padding: 10px 0;
		margin-bottom: 10px;
		border-bottom: 1px solid #f5f5f5;
	}

	.operation-btn {
		margin-left: 5px;
	}

	.dialog-form.el-form-item {
		margin-bottom: 15px;
	}

	.el-table {
		margin-bottom: 15px;
	}

	:deep(.el-dialog__body) {
		max-height: 60vh;
		overflow-y: auto;
		padding: 20px;
	}
</style>